# core/autoloads/game_manager.gd (Autoload单例)
#GameManager.gd
#├── 状态机管理（枚举/验证/切换）
#├── 场景加载控制（异步加载/进度更新）
#├── 暂停控制（状态存储/恢复）
#├── 资源生命周期管理（释放/缓存）
#└── UI控制（加载界面/进度反馈）
extends Node

### === 状态机定义 ===
enum GameState {
	MAIN_MENU,
	CHARACTER_SELECT,
	PATH_SELECTION,
	BATTLE,
	SETTLEMENT,
	PAUSED
}

var current_state: GameState = GameState.MAIN_MENU
#var _target_scene_path: String = ""
var _pending_scene: PackedScene

### === 加载UI控制 ===
var _loading_ui: Control
var _progress_bar: ProgressBar
var _loading_tip: Label

var _target_progress: float = 0.0

### === 生命周期管理 ===
func _ready() -> void:
	_EventBus.scene_transition_started.connect(_on_scene_transition_requested)
	_EventBus.game_paused.connect(_toggle_pause_state)

func _process(delta: float) -> void:
	if _loading_ui != null and _loading_ui.visible:
		_progress_bar.value = lerp(_progress_bar.value, _target_progress, delta * 5)
		
### === 公开接口 ===
func change_state(new_state: GameState, scene_path: String = "") -> void:
	if new_state == current_state: 
		return
	
	_validate_state_transition(new_state)
	_cleanup_old_state_resources()
	
	if !scene_path.is_empty():
		_load_new_scene_async(scene_path)
	
	current_state = new_state
	_EventBus.game_state_changed.emit(current_state)

### === 核心逻辑 ===
func _validate_state_transition(target_state: GameState) -> void:
	var allowed_transitions := {
		GameState.MAIN_MENU: [GameState.CHARACTER_SELECT],
		GameState.CHARACTER_SELECT: [GameState.PATH_SELECTION],
		GameState.PATH_SELECTION: [GameState.BATTLE],
		GameState.BATTLE: [GameState.SETTLEMENT],
		GameState.SETTLEMENT: [GameState.PATH_SELECTION, GameState.MAIN_MENU],
		GameState.PAUSED: [current_state]  # 可返回任意前状态
	}
	assert(
		target_state in allowed_transitions[current_state],
		"非法状态切换: %s → %s" % [GameState.keys()[current_state], GameState.keys()[target_state]]
	)

func _load_new_scene_async(scene_path: String) -> void:
	_show_loading_ui()
	ResourceLoader.load_threaded_request(scene_path)
	
	while ResourceLoader.load_threaded_get_status(scene_path) == ResourceLoader.THREAD_LOAD_IN_PROGRESS:
		_update_loading_progress(scene_path)
		var progress := []
		ResourceLoader.load_threaded_get_status(scene_path, progress)
		if progress[0] >= 0.8:  # 完成80%即可进入
			break
		await get_tree().process_frame
	
	_pending_scene = ResourceLoader.load_threaded_get(scene_path)
	get_tree().change_scene_to_packed(_pending_scene)
	_hide_loading_ui()

func _cleanup_old_state_resources() -> void:
	var sceneloader : SceneLoader = SceneLoader.new()
	if _pending_scene:
		_pending_scene.take_over_path("")  # 防止资源重复释放
	match current_state:
		GameState.BATTLE:
			sceneloader.release_battle_resources()
		GameState.PATH_SELECTION:
			sceneloader.release_path_resources()
	sceneloader.queue_free()

### === 暂停控制 ===
func _toggle_pause_state(is_paused: bool) -> void:
	get_tree().paused = is_paused
	current_state = GameState.PAUSED if is_paused else _get_previous_state()

func _get_previous_state() -> GameState:
	return GameState.values().max() if current_state == GameState.PAUSED else current_state

### === 信号处理 ===
func _on_scene_transition_requested(scene_path: String) -> void:
	change_state(_deduce_state_from_scene(scene_path), scene_path)

func _deduce_state_from_scene(path: String) -> GameState:
	var state_map := {
		"res://ui/menus/main_menu.tscn": GameState.MAIN_MENU,
		"res://gameplay/route_selection/path_selector.tscn": GameState.PATH_SELECTION,
		"res://gameplay/battle/battle_scene.tscn": GameState.BATTLE
	}
	return state_map.get(path, current_state)

func _initialize_loading_ui() -> void:
	# 延迟初始化防止场景未加载时的空引用
	if not _loading_ui:
		_loading_ui = get_tree().root.get_node("HUD/LoadingLayer")
		_progress_bar = _loading_ui.get_node("ProgressBar")
		_loading_tip = _loading_ui.get_node("Tips")

func _show_loading_ui() -> void:
	_initialize_loading_ui()
	_loading_ui.visible = true
	_loading_tip.text = _get_random_loading_tip()
	_progress_bar.value = 0

func _update_loading_progress(scene_path: String) -> void:
	var progress := []
	var status = ResourceLoader.load_threaded_get_status(scene_path, progress)
	_target_progress = progress[0] * 100
	
	if status == ResourceLoader.THREAD_LOAD_IN_PROGRESS:
		_progress_bar.value = progress[0] * 100
		_loading_tip.text = "%s (%d%%)" % [
			_get_random_loading_tip(),
			ceil(progress[0] * 100)
		]

func _hide_loading_ui() -> void:
	_loading_ui.visible = false
	_EventBus.emit_signal("loading_completed")

### === 辅助方法 ===
func _get_random_loading_tip() -> String:
	var tips := [
		"正在整理登山装备...",
		"分析华山地形数据...",
		"加载环保知识彩蛋...",
		"初始化天气系统..."
	]
	return tips[randi() % tips.size()]
